package controller;

import beans.LogEnum;
import beans.Model;
import beans.Task;
import dao.ModelDao;
import net.TaskOperator;
import net.sf.json.JSONObject;
import portal.controller.BaseServlet;

import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;

import utils.ExternalInterfaceParseUtil;
import utils.FileOper;
import utils.ParseUtil;
import utils.UserLogUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * 用于解析生成一个task的json。保存到数据库，并启动一个任务
 * data:提供必要的任务信息，包括运行参数、算法输入、算法输出
 * modelId：提供模型id
 */
public class BatchTaskCommit extends BaseServlet {
	@Autowired
	TaskOperator taskOperator ;
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String data = request.getParameter("data");
        JSONObject paramsJson = JSONObject.fromObject(data);
        String modelIdString = paramsJson.getString("modelId");
        String userId = (String) request.getSession().getAttribute("userId");
        int modelIdInt = Integer.parseInt(modelIdString);
        ExternalInterfaceParseUtil externalInterfaceParseUtil = new ExternalInterfaceParseUtil();
        Task task = externalInterfaceParseUtil.createTaskByModelIdAndParamsJson(userId, modelIdInt,paramsJson);
        task.setJson(FileOper.writeTaskJson(FileOper.genTaskJsonFilePath(), task.getJson()));
        String taskHash = UUID.randomUUID().toString().substring(0,20);
        com.alibaba.fastjson.JSONObject result = taskOperator.saveAndStartTask(task,taskHash);
        response.getWriter().write(result.toString());
        // 日志记录
        UserLogUtil.dbLog(LogEnum.historyTask,
                LogEnum.useModelIdCreateTaskAndRunTask,
                userId,
                LogEnum.model.getValue()+"编号："+modelIdString);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}